<template>
  <div class="bank-card-container">
    <!-- 顶部导航栏 -->
    <div class="bank-card-header">
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
      </div>
      <div class="header-title">{{ t('bankCard.title') }}</div>
      <div class="placeholder"></div>
    </div>
    
    <!-- 提示信息 -->
    <div class="bank-card-tip">
      绑定银行卡，方便快捷收款和还款~
    </div>
    
    <!-- 银行卡列表区域 -->
    <div class="bank-card-content">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <div v-else-if="bankCardStore.bankCards.length === 0" class="empty-container">
        <el-empty :description="t('bankCard.noCards')">
          <el-button type="primary" @click="showAddCardDialog">
            {{ t('bankCard.addFirstCard') }}
          </el-button>
        </el-empty>
      </div>
      
      <div v-else class="bank-cards">
        
        <div 
          v-for="card in bankCardStore.bankCards" 
          :key="card.id" 
          class="bank-card"
          :class="{ 'is-default': card.isDefault === 1 }"
        >
          <div class="bank-card-header">
            <div class="bank-name">{{ card.bankName }}</div>
            <div class="card-type">
              {{ card.cardType === 0 ? t('bankCard.debitCard') : t('bankCard.creditCard') }}
            </div>
          </div>
          <div class="card-no">{{ formatCardNo(card.cardNo) }}</div>
          <div class="card-holder">{{ card.holderName }}</div>
          <div class="card-actions">
            <el-tag v-if="card.isDefault === 1" type="success" size="small">
              {{ t('bankCard.defaultCard') }}
            </el-tag>
            <div class="action-buttons">
              <el-button 
                v-if="card.isDefault !== 1" 
                type="primary" 
                size="small" 
                @click="setDefaultCard(card.id)"
              >
                {{ t('bankCard.setDefault') }}
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                plain 
                @click="editCard(card)"
              >
                {{ t('bankCard.edit') }}
              </el-button>
              <el-button 
                v-if="card.isDefault !== 1" 
                type="danger" 
                size="small" 
                plain 
                @click="deleteCard(card.id)"
              >
                {{ t('bankCard.delete') }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 添加/编辑银行卡对话框 -->
    <el-dialog
      v-model="cardDialogVisible"
      :title="isEditing ? t('bankCard.editCard') : t('bankCard.addCard')"
      width="90%"
      top="15vh"
      class="bank-card-dialog"
    >
      <el-form
        ref="cardFormRef"
        :model="cardForm"
        :rules="cardRules"
        label-width="90px"
        class="bank-card-form"
      >
        <el-form-item :label="t('bankCard.cardNo')" prop="cardNo">
          <el-input 
            v-model="cardForm.cardNo" 
            :placeholder="t('bankCard.cardNoPlaceholder')"
            :disabled="isEditing"
          />
        </el-form-item>
        <el-form-item :label="t('bankCard.bankName')" prop="bankName">
          <el-select 
            v-model="cardForm.bankName" 
            :placeholder="t('bankCard.selectBank')"
            @change="handleBankChange"
            style="width: 100%"
          >
            <el-option
              v-for="bank in bankList"
              :key="bank.code"
              :label="bank.name"
              :value="bank.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('bankCard.holderName')" prop="holderName">
          <el-input 
            v-model="cardForm.holderName" 
            :placeholder="t('bankCard.holderNamePlaceholder')"
          />
        </el-form-item>
        <el-form-item :label="t('bankCard.phone')" prop="phone">
          <el-input 
            v-model="cardForm.phone" 
            :placeholder="t('bankCard.phonePlaceholder')"
          />
        </el-form-item>
    <!--   <el-form-item :label="t('bankCard.cardType')" prop="cardType">
          <el-radio-group v-model="cardForm.cardType">
            <el-radio :label="0">{{ t('bankCard.debitCard') }}</el-radio>
            <el-radio :label="1">{{ t('bankCard.creditCard') }}</el-radio>
          </el-radio-group>
        </el-form-item>--> 
        <el-form-item :label="t('bankCard.isDefault')" prop="isDefault">
          <el-switch v-model="cardForm.isDefault" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cardDialogVisible = false">
            {{ t('bankCard.cancel') }}
          </el-button>
          <el-button type="primary" @click="saveCard" class="save-button">
            {{ t('bankCard.save') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 提交按钮 -->
    <div class="submit-button-container" v-if="bankCardStore.bankCards.length > 0">
      <el-button type="primary" class="submit-button" @click="showAddCardDialog">
        {{ t('bankCard.addCard') }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useUserStore, useBankCardStore } from 'store';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import bankService from '@/services/bankService';

// 国际化
const { t } = useI18n();

// 路由
const router = useRouter();

// 用户状态
const userStore = useUserStore();
const bankCardStore = useBankCardStore();

// 返回上一页
const goBack = () => {
  router.back();
};

// 加载状态
const loading = ref(false);

// 银行卡对话框
const cardDialogVisible = ref(false);
const isEditing = ref(false);
const cardFormRef = ref(null);

// 银行卡表单
const cardForm = reactive({
  id: null,
  userId: null,
  cardNo: '',
  bankName: '',
  bankCode: '',
  holderName: '',
  phone: '',
  cardType: 0,
  isDefault: 0
});

// 银行列表
const bankList = [
  { name: '中国工商银行', code: 'ICBC' },
  { name: '中国农业银行', code: 'ABC' },
  { name: '中国银行', code: 'BOC' },
  { name: '中国建设银行', code: 'CCB' },
  { name: '交通银行', code: 'COMM' },
  { name: '中国邮政储蓄银行', code: 'PSBC' },
  { name: '招商银行', code: 'CMB' },
  { name: '中信银行', code: 'CITIC' },
  { name: '中国光大银行', code: 'CEB' },
  { name: '华夏银行', code: 'HXB' },
  { name: '中国民生银行', code: 'CMBC' },
  { name: '广发银行', code: 'GDB' },
  { name: '平安银行', code: 'PAB' },
  { name: '浦发银行', code: 'SPDB' },
  { name: '兴业银行', code: 'CIB' }
];

// 表单验证规则
const cardRules = {
  cardNo: [
    { required: true, message: t('bankCard.cardNoRequired'), trigger: 'blur' },
    { pattern: /^\d{16,19}$/, message: t('bankCard.cardNoFormat'), trigger: 'blur' }
  ],
  bankName: [
    { required: true, message: t('bankCard.bankNameRequired'), trigger: 'change' }
  ],
  holderName: [
    { required: true, message: t('bankCard.holderNameRequired'), trigger: 'blur' }
  ],
  phone: [
    { required: true, message: t('bankCard.phoneRequired'), trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: t('bankCard.phoneFormat'), trigger: 'blur' }
  ],
  cardType: [
    { required: true, message: t('bankCard.cardTypeRequired'), trigger: 'change' }
  ]
};

// 格式化银行卡号
const formatCardNo = (cardNo) => {
  if (!cardNo) return '';
  return cardNo.replace(/(\d{4})(?=\d)/g, '$1 ');
};

// 处理银行选择变化
const handleBankChange = (bankName) => {
  const bank = bankList.find(item => item.name === bankName);
  if (bank) {
    cardForm.bankCode = bank.code;
  }
};

// 显示添加银行卡对话框
const showAddCardDialog = () => {
  isEditing.value = false;
  resetCardForm();
  cardDialogVisible.value = true;
};

// 编辑银行卡
const editCard = (card) => {
  isEditing.value = true;
  Object.assign(cardForm, card);
  cardDialogVisible.value = true;
};

// 保存银行卡
const saveCard = () => {
  if (!cardFormRef.value) return;
  
  cardFormRef.value.validate((valid) => {
    if (!valid) return;
    
    cardForm.userId = userStore.userId;
    loading.value = true;
    
    const promise = isEditing.value 
      ? bankService.updateBankCard(cardForm)
      : bankService.addBankCard(cardForm);
    
    promise
      .then(() => {
          ElMessage.success(isEditing.value ? t('bankCard.updateSuccess') : t('bankCard.addSuccess'));
          cardDialogVisible.value = false;
      })
      .catch(error => {
        ElMessage.error(error.message || (isEditing.value ? t('bankCard.updateFailed') : t('bankCard.addFailed')));
      })
      .finally(() => {
        loading.value = false;
      });
  });
};

// 设置默认银行卡
const setDefaultCard = (id) => {
  loading.value = true;
  console.log(id, userStore.userId);
  bankService.setDefaultBankCard(id, userStore.userId)
    .then(() => {
        ElMessage.success(t('bankCard.setDefaultSuccess'));
    })
    .catch(error => {
      ElMessage.error(error.message || t('bankCard.setDefaultFailed'));
    })
    .finally(() => {
      loading.value = false;
    });
};

// 删除银行卡
const deleteCard = (id) => {
  ElMessageBox.confirm(
    t('bankCard.deleteConfirm'),
    t('bankCard.deleteTitle'),
    {
      confirmButtonText: t('bankCard.confirm'),
      cancelButtonText: t('bankCard.cancel'),
      type: 'warning'
    }
  ).then(() => {
    loading.value = true;
    
    bankService.deleteBankCard(id, userStore.userId)
      .then(() => {
        ElMessage.success(t('bankCard.deleteSuccess'));
      })
      .catch(error => {
        ElMessage.error(error.message || t('bankCard.deleteFailed'));
      })
      .finally(() => {
        loading.value = false;
      });
  }).catch(() => {
    // 取消删除
  });
};

// 重置银行卡表单
const resetCardForm = () => {
  cardForm.id = null;
  cardForm.userId = null;
  cardForm.cardNo = '';
  cardForm.bankName = '';
  cardForm.bankCode = '';
  cardForm.holderName = '';
  cardForm.phone = '';
  cardForm.cardType = 0;
  cardForm.isDefault = 0;
};

// 获取银行卡列表
onMounted(() => {
  loading.value = true;
  try {
    bankService.getBankCards(userStore.userId);
  } finally {
    loading.value = false;
  }
});
</script>

<style scoped>
.bank-card-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 顶部导航栏样式 */
.bank-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  background-color: #3a4a6d;
  color: white;
  padding: 0 15px;
}

.back-button {
  font-size: 20px;
  cursor: pointer;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
}

.placeholder {
  width: 20px;
}

/* 提示信息样式 */
.bank-card-tip {
  background-color: #f0f0f0;
  padding: 10px 15px;
  font-size: 14px;
  color: #666;
}

/* 内容区域样式 */
.bank-card-content {
  margin-top: 10px;
  background-color: white;
  padding: 15px;
}

.loading-container, .empty-container {
  padding: 20px 0;
}

.add-card-button-container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

.add-card-button {
  background-color: #3a4a6d;
  border-color: #3a4a6d;
}

.bank-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.bank-card {
  background: linear-gradient(135deg, #42a5f5 0%, #2196f3 100%);
  color: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  }
  
  &.is-default {
    background: linear-gradient(135deg, #66bb6a 0%, #43a047 100%);
  }
  
  .bank-card-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    background-color: transparent;
    padding: 0;
    height: auto;
    
    .bank-name {
      font-weight: bold;
      font-size: 18px;
    }
    
    .card-type {
      font-size: 14px;
      opacity: 0.8;
    }
  }
  
  .card-no {
    font-size: 20px;
    letter-spacing: 2px;
    margin-bottom: 20px;
  }
  
  .card-holder {
    font-size: 16px;
    margin-bottom: 20px;
    opacity: 0.9;
  }
  
  .card-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .action-buttons {
      display: flex;
      gap: 10px;
    }
  }
}

/* 对话框样式 */
:deep(.bank-card-dialog .el-dialog__header) {
  text-align: center;
  font-weight: bold;
  padding: 15px 0;
}

:deep(.bank-card-dialog .el-dialog__body) {
  padding: 10px 15px;
}

:deep(.bank-card-dialog .el-dialog__footer) {
  padding: 10px 15px 20px;
}

.bank-card-form {
  max-width: 100%;
}

:deep(.bank-card-form .el-form-item) {
  margin-bottom: 15px;
}

:deep(.bank-card-form .el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

:deep(.bank-card-form .el-form-item__content) {
  flex: 1;
}

:deep(.bank-card-form .el-input__wrapper) {
  width: 100%;
}

.save-button {
  background-color: #3a4a6d;
  border-color: #3a4a6d;
}

/* 提交按钮样式 */
.submit-button-container {
  padding: 20px 15px;
  margin-top: auto;
}

.submit-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
  background-color: #3a4a6d;
  border-color: #3a4a6d;
}
</style>